package com.ray.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ray.bean.DepartmentDropdownBean;
import com.ray.bean.EquipmentBean;
import com.ray.exception.ServiceException;
import com.ray.pojo.MyUser;
import com.ray.protocol.constants.AccessEquipmentCode;
import com.ray.service.EquipmentService;
import com.ray.service.WeiXinService;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil;
import com.ray.util.qiniu.QiniuConfig;
import com.ray.util.qiniu.QiniuUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备信息控制器
 * <p>
 * Title: EquipmentControllerf
 * </p>
 * <p>
 * Description:
 * </p>
 *
 * @author 李斌
 * @date 2018年4月12日
 */
@SuppressWarnings("rawtypes")
@RestController
@RequestMapping("/equipment")
public class EquipmentController {

    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private WeiXinService weiXinService;

    /**
     * @return Map
     * @throws ServiceException 添加设备信息
     * @throws
     * @date 2018年4月12日 上午9:44:14
     * @author 李斌
     */
    @RequestMapping("/addEquipment")
    public Map addEquipment(HttpServletRequest request) throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        equipmentService.addEquipment(map);
        return ResponseUtil.ResponseResult(ReturnStringUtil.ADD_SUCCESS);
    }

    @RequestMapping("/delEquipment")
    public Map delEquipment(HttpServletRequest request) throws ServiceException{
        Map map = RequestUtil.getRequestAllParam(request);
        equipmentService.delEquipment(map);
        return ResponseUtil.ResponseResult(ReturnStringUtil.DELETE_SUCCESS);
    }

    @RequestMapping("/checkEquipmentNoUnique")
    public Map checkEquipmentNoUnique(HttpServletRequest request){
        Map<String,String> map=new HashMap<>();
        String equipmentNo=request.getParameter("equipmentNo");
        if(null==equipmentNo) throw new ServiceException("设备编号不能为空");
        map.put("equipmentNo",equipmentNo);
        return ResponseUtil.ResponseResult(equipmentService.checkEquipmentNoUnique(map));
    }

    /**
     * @return Map
     * @throws ParseException 获取所有设备信息数据(分页)
     * @throws
     * @date 2018年4月12日 下午2:53:08
     * @author 李斌
     */
    @RequestMapping("/getAllEquipment")
    public Map getAllEquipment(HttpServletRequest request)
            throws ServiceException, ParseException {
        Map map = RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(equipmentService
                .getAllEquipment(map));
    }

    /**
     * 通过设备信息获取设备
     *
     * @return Map
     * @throws
     * @date 2018年4月12日 上午10:14:40
     * @author 李斌
     */
    @RequestMapping("/getEquipmentByDetail")
    public Map getEquipmentByDetail(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(equipmentService
                .getEquipmentByDetail(map));
    }

    /**
     * 修改设备信息
     *
     * @return Map
     * @throws
     * @date 2018年4月12日 下午2:53:35
     * @author 李斌
     */
    @RequestMapping("/updateEquipment")
    public Map updateEquipment(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        equipmentService.updateEquipment(map);
        return ResponseUtil.ResponseResult(ReturnStringUtil.UPDATE_SUCCESS);
    }

    /**
     * @return Map
     * @throws IOException
     * @throws ServiceException 上传设备图片
     * @throws
     * @date 2018年4月12日 下午1:43:13
     * @author 李斌
     */
    @RequestMapping("/uploadFileByEquipmentImage")
    public Map uploadFileByEquipmentImage(HttpServletRequest request,
                                          MultipartFile file) throws ServiceException, IOException {
        String path = QiniuUploadUtils.uploadFileByStream(
                QiniuConfig.accessKey, QiniuConfig.secretKey,
                QiniuConfig.bucketShinehaopic, file.getInputStream(), null,
                QiniuConfig.bucketShinehaopicUrlPrefix);
        return ResponseUtil.ResponseResult(path);
    }

    /**
     * @return Map
     * @throws ServiceException 获取部门和车间
     * @throws
     * @date 2018年4月13日 上午8:04:05
     * @author 李斌
     */
    @RequestMapping("/getDepartmentDropdown")
    public Map getDepartmentAndWorkShop(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        List<DepartmentDropdownBean> departments = equipmentService
                .getDepartmentAndWorkShop(map);
        return ResponseUtil.ResponseResult(departments);
    }

    /**
     * 检查设备编号是否存在
     *
     * @param request
     * @return
     * @throws ServiceException
     */
    @RequestMapping("/checkNoUnique")
    public Map checkNoUnique(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        int count = equipmentService.checkCountByNo(map);
        return ResponseUtil.ResponseResult(count);
    }

    /**
     * 获取设备加工信息
     *
     * @param request map参数
     *                departmentId
     *                （部门id）
     *                workShopId
     *                (车间id)
     * @return
     * @throws ServiceException
     * @author natelu
     */
    @RequestMapping("/getAllMachine")
    public Map getAllMachine(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(equipmentService.getAllMachine(map));
    }

    /**
     * 获取电气监控数据
     *
     * @param request map 参数
     * @return
     * @throws ServiceException departmentId
     *                          (部门id)
     *                          workShopId
     *                          (车间id)
     *                          start
     *                          (开始条数)
     *                          length
     *                          (结束条数)
     *                          equipmentNo
     *                          (设备编号，查询单号)
     * @author natelu
     */
    @RequestMapping("/getEcsMonitor")
    public Map getEcsMonitor(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(equipmentService.getEcsMonitor(map));
    }

    /**
     * 设置设备生产订单
     *
     * @param request map 参数
     *                equipmentNo
     *                (设备编号)
     *                orderId
     *                (系统订单编号)
     *                orderNo
     *                (选择的单号)
     *                adjustingMachineCount
     *                (调机数 可不输入)
     *                processIdentify
     *                (工序id )
     * @return
     * @throws ServiceException
     * @author nate
     */
    @RequestMapping("/setEquipmentMachineOrder")
    public Map setEquipmentMachineOrder(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        equipmentService.setEquipmentMachineOrder(map);
        return ResponseUtil.ResponseResult(ReturnStringUtil.SET_SUCCESS);
    }


    /**
     * 获取设备稼动率
     *
     * @param request map参数
     *                departmentId
     *                (部门id)
     *                workShopId
     *                (车间id)
     *                startTime
     *                (开始时间，毫秒数)
     *                endTime
     *                (结束时间)
     *                start
     *                (分页参数)
     *                length
     *                (分页参数)
     *                equipmentNo
     *                (设备编号，查询单条数据)
     * @throws ServiceException
     */
    @RequestMapping("/getEquipmentCropMobility")
    public Map getEquipmentCropMobility(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(equipmentService
                .getEquipmentCropMobility(map));
    }

    /**
     * @param request
     * @throws ServiceException
     * @Title: getEquipmentName
     * @author: 李宇航
     * @Description: 获取未关联总开关的所有设备
     * @return: Map
     */
    @RequestMapping("/getNoMainSwitchEquipment")
    public Map getNoMainSwitchEquipment(HttpServletRequest request)
            throws ServiceException {
        Map map = RequestUtil.getRequestAllParam(request);
        return ResponseUtil.ResponseResult(equipmentService
                .getNoMainSwitchEquipment(map));
    }

    /**
     * 看板获取设备信息
     * @param request
     * @return
     * @throws ServiceException
     */
    @RequestMapping("/getEquipmentBoard")
    public Map getEquipmentBoard(HttpServletRequest request)
            throws ServiceException {
    	Map<String, String> param = RequestUtil.getRequestAllParamNotLogin2String(request);
    	if(null==param.get("equipmentNo") || "".equals(param.get("equipmentNo"))) {
    		param = RequestUtil.getRequestAllParam2String(request);
    	}
        return ResponseUtil.ResponseResult(equipmentService.getEquipmentBoard(param));
    }
    
    
    /**
     * 看板获取设备能耗信息
     * @param request
     * @return
     * @throws ServiceException
     */
    @RequestMapping("/getMachineUseElectric")
    public Map getMachineUseElectric(HttpServletRequest request)
    		throws ServiceException {
    	Map<String, String> param = RequestUtil.getRequestAllParamNotLogin2String(request);
    	if(null==param.get("equipmentNo") || "".equals(param.get("equipmentNo"))) {
    		param = RequestUtil.getRequestAllParam2String(request);
    	}
    	return ResponseUtil.ResponseResult(equipmentService.getMachineUseElectric(param));
    }

    /**
     * @param data
     * @throws ServiceException
     * @Title: getNumberOfThrowStuff
     * @author:李宇航
     * @Description: 获取投料数
     * @return: Object
     */
    @RequestMapping("/accessEquipmentServer")
    public Object accessEquipmentServer(@RequestBody String data) {
        JSONObject jsonObject = JSON.parseObject(data);
        data = jsonObject.getString("data");
        switch (jsonObject.getInteger("code")) {
            //获取订单需求投料数
            case AccessEquipmentCode.GET_NUMBER_OF_THROW_STUFF: {
                return equipmentService.getNumberOfThrowStuff(data);
            }
            //向服务器发送数据
            case AccessEquipmentCode.PUSH_EQUIPMENT_BOARD_DYNAMIC_DATA: {
                return equipmentService.pushEquipmentBoardDynamicData(data);
            }
        }
        return -1;
    }


    @RequestMapping("/getDynamicEquipmentBoardData")
    public Object getEquipmentBoardDynamicData(HttpServletRequest request) throws ServiceException {
        Map<String, String> param = RequestUtil.getRequestAllParamNotLogin2String(request);
        List<String> data = JSON.parseArray(param.get("equipmentNos"), String.class);
        return ResponseUtil.ResponseResult(equipmentService.getEquipmentBoardDynamicData(data));
    }
    @RequestMapping("/getEquipmentDetailByUrlParam")
    public Object getEquipmentDetailByUrlParam(HttpServletRequest request){
        Map<String, String> param = RequestUtil.getRequestAllParam2String(request);
        return  ResponseUtil.ResponseResult(equipmentService.getEquipmentDetailByUrlParam(param));
    }
    
    @RequestMapping("/getAllEquipmentPrice")
    public Object getAllEquipmentPrice(HttpServletRequest request){
    	Map<String, String> param = RequestUtil.getRequestAllParam2String(request);
    	return  ResponseUtil.ResponseResult(equipmentService.getAllEquipmentPrice(param));
    }
    
    /**
     * 获取设备日利用率
     * month
     * @param request
     * @return
     * @throws CloneNotSupportedException 
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/getEquipmentDailyUseRate")
    public Map getEquipmentDailyUseRate(HttpServletRequest request) throws CloneNotSupportedException {
    	Map<String, String> param = RequestUtil.getRequestAllParamNotLogin2String(request);
    	if(null==param.get("equipmentNo") || "".equals(param.get("equipmentNo"))) {
    		param = RequestUtil.getRequestAllParam2String(request);
    	}
    	return ResponseUtil.ResponseResult(equipmentService.getEquipmentDailyUseRate(param));
    }
    
    /**
     * 获取设备月利用率
     * year
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/getEquipmentMonthUseRate")
    public Map getEquipmentMonthUseRate(HttpServletRequest request) {
    	Map<String, String> param = RequestUtil.getRequestAllParamNotLogin2String(request);
    	if(null==param.get("equipmentNo") || "".equals(param.get("equipmentNo"))) {
    		param = RequestUtil.getRequestAllParam2String(request);
    	}
    	return ResponseUtil.ResponseResult(equipmentService.getEquipmentMonthUseRate(param));
    }
    
    
    /**
     * 获取设备警报详情
     * 前端分页前端筛选
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/getEquipmentAlarmCode")
    public Map getEquipmentAlarmCode(HttpServletRequest request) {
    	Map map=RequestUtil.getRequestAllParam(request);
    	return ResponseUtil.ResponseResult(equipmentService.getEquipmentAlarmCode(map));
    }
    
    /**
     * 添加设备警报详情
     * jsonArray
     * typeName 类型名称（必填）
     * alarmCode 警报代码（必填）
     * codeDescribe 警报描述（必填）
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/addEquipmentAlarmCode")
    public Map addEquipmentAlarmCode(HttpServletRequest request) {
    	Map map=RequestUtil.getRequestAllParam(request);
    	return ResponseUtil.ResponseResult(equipmentService.addEquipmentAlarmCode(map));
    }
    
    /**
     * 删除设备警报详情
     * jsonArray
     * typeName 类型名称（必填）
     * alarmCode 警报代码（必填）
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/deleteEquipmentAlarmCode")
    public Map deleteEquipmentAlarmCode(HttpServletRequest request) {
    	Map map=RequestUtil.getRequestAllParam(request);
    	return ResponseUtil.ResponseResult(equipmentService.deleteEquipmentAlarmCode(map));
    }
    
    
    
    /**
     * 修改设备警报详情
     * jsonArray
     * id id
     * codeDescribe 警报描述
     * isShow  是否显示
     * @param request
     * @return
     * @throws ServiceException
     */
    @ResponseBody
    @RequestMapping("/updateEquipmentAlarmCode")
    public Map updateEquipmentAlarmCode(HttpServletRequest request) {
    	Map map=RequestUtil.getRequestAllParam(request);
    	return ResponseUtil.ResponseResult(equipmentService.updateEquipmentAlarmCode(map));
    }
    
    
    
    /**
     * 获取工序能耗看板数据
     * 
     */
    @ResponseBody
    @RequestMapping("/getProcessConsumptionData")
    public Map getProcessConsumptionData(HttpServletRequest request) {
    	Map map=RequestUtil.getRequestAllParam(request);
    	return ResponseUtil.ResponseResult(equipmentService.getProcessConsumptionData(map));
    }

}
